<template>
  <el-select
    v-model="model"
    :disabled="disabled"
    :placeholder="placeholder"
    @change="handleChange"
  >
    <el-option
      v-for="item of computedList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { getAllUserByUnitIdAndCode } from '@/api/sys/userManage'

const model = defineModel<number>()
const emit = defineEmits(['change'])

const { departmentId, unitId, roleCode, disabled, placeholder } = defineProps<{
  departmentId?: number | undefined
  unitId?: number | undefined
  roleCode?: string | undefined
  disabled?: boolean
  placeholder?: string
}>()

const list = ref([])

watch(
  () => [departmentId, unitId],
  async ([value1, value2]: [number, number]) => {
    console.log(value1, value2)
    if (!value1 && !value2) {
      list.value = []
      return
    }
    await getList()
  },
  {
    immediate: true,
  },
)

const computedList = computed(() => {
  if (roleCode) {
    return list.value
      .filter((item) => item.roleCode === roleCode)
      .map((item) => ({ ...item, label: item.name, value: item.id }))
  } else {
    return list.value.map((item) => ({
      ...item,
      label: item.name,
      value: item.id,
    }))
  }
})

async function getList() {
  const { data } = await getAllUserByUnitIdAndCode({
    departmentId,
    unitId,
    roleCode,
  })
  if (data.status === 200) {
    list.value = data.data
  }
}

function handleChange(value: number) {
  emit(
    'change',
    computedList.value.find((item) => item.value === value),
  )
}
</script>

<style scoped lang="scss"></style>
